var ids, password2, yanzheng, input2, p1, form, password
init();
function init() {
    password2 = document.querySelector("#password2")
    yanzheng = document.querySelector(".yzm")
    p1 = document.querySelector(".p1")
    form = document.querySelector("form")
    form.addEventListener("input", inputHandler)
    form.addEventListener("submit", submitHandler)
    input2 = document.querySelector("#input3");
    password = document.querySelector("#password")

    form.addEventListener("submit", submitHandler)
    yanzheng.addEventListener("click", clickHandler)
}


function clickHandler(e) {
    p1.style.display = "none"
    var Num = "";
    for (var i = 0; i < 6; i++) {
        Num += Math.floor(Math.random() * 10);
    }
    input2.value = Num

}


function inputHandler(e) {
    if (e.target.name === "input1") e.target.value = e.target.value.replace(/\D/g, "");
    if (ids) return;
    ids = setTimeout(function (input) {
        clearTimeout(ids);
        ids = undefined;
        setInputStyle(input)
    }, 500, e.target);
}

function setInputStyle(input) {
    if (input.name === "input3") {
        if (judgeInput(input.name, input.value)) {
            p1.style.display = "none"
        } else {
            p1.style.display = "block"
        }
    } else {
        if (judgeInput(input.name, input.value)) {
            input.nextElementSibling.innerHTML = "正确"
            input.nextElementSibling.style.color = "rgb(0,255,0)";
        } else {
            input.nextElementSibling.innerHTML = "错误"
            input.nextElementSibling.style.color = "rgb(255,0,0)";
        }
    }

}
function judgeInput(name, value) {
    var arr = document.querySelector('#password').value
    switch (name) {
        case "input1":
            return /^\d{11}$/.test(value);
        case "input2":
            return /^(?=\D+\d)\w{8,18}$/.test(value);
        case "input3":
            return value.length == 6 ? true : false
        case "queren":
            return value == arr;
    }
}
async function submitHandler(e) {
    e.preventDefault();
    var fd = new FormData(this)
    var obj = {};
    for (var [name, value] of fd) {
        if (!judgeInput(name, value)) {
            document.querySelector(`[name=${name}]`).focus();
            return;
        }
        if (name === "input1" || name === "input2") {
            obj[name] = value;
        }
    }

    var response = await fetch("http://localhost:3860/zhuce", {
        method: "POST",
        body: JSON.stringify(obj)
    });
    var data = await response.json();


    if (data === "注册成功") {
        alert("注册成功")
        location.href = "../sass/record.html"
    } else {
        alert("注册失败")
    }

}

